package cos

import (
	"context"
	"fmt"
	"github.com/tencentyun/cos-go-sdk-v5"
	"io"
	"log"
	"net/http"
	"net/url"
	"sync"
)

const (
	COS_HOST    = "https://dancers-1253740002.cos.ap-shanghai.myqcloud.com"
	COS_RAW_URL = "https://cos.ap-shanghai.myqcloud.com"
	SECRET_ID   = "AKIDPsVGwfO0hUMB10AFLNLPg2eyHWefdYM3"
	SECRET_KEY  = "jLo7FJEz7OxOyT7wvskWFtSpCYt5AKg0"
)

type CosIns struct {
	client *cos.Client
}

var cosIns *CosIns
var CosOnce sync.Once

// Instance 考虑到事务的操作便利，所以将所有的数据都放到序号0数据库中
func Instance() *CosIns {
	// 将 examplebucket-1250000000 和 COS_REGION修改为真实的信息
	u, _ := url.Parse(COS_HOST)
	// 用于Get Service 查询，默认全地域 service.cos.myqcloud.com
	su, _ := url.Parse(COS_RAW_URL)
	b := &cos.BaseURL{BucketURL: u, ServiceURL: su}
	CosOnce.Do(func() {
		cosIns = &CosIns{
			client: cos.NewClient(b, &http.Client{
				Transport: &cos.AuthorizationTransport{
					SecretID:  SECRET_ID,
					SecretKey: SECRET_KEY,
				},
			}),
		}
	})
	return cosIns
}

// 上传文件并返回下载链接
func (ins *CosIns) PutFile(key string, reader io.Reader) (url string, err error) {
	_, err = ins.client.Object.Put(context.Background(), key, reader, nil)
	if err != nil {
		return "", err
	}
	url = fmt.Sprint(COS_HOST, "/", key)
	log.Println(url)
	return url, err
}
